package cn.powerone.scm.service.impl;

import java.math.BigDecimal;
import java.util.List;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.common.utils.StringUtils;
import cn.powerone.scm.domain.*;
import cn.powerone.scm.service.IScmCustomerOrdersService;
import cn.powerone.scm.service.IScmCustomerQuotesService;
import cn.powerone.scm.service.IScmProjectProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.powerone.scm.mapper.ScmCustomerOrderItemsMapper;
import cn.powerone.scm.service.IScmCustomerOrderItemsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户订单明细Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-04
 */
@Service
public class ScmCustomerOrderItemsServiceImpl implements IScmCustomerOrderItemsService 
{
    @Autowired
    private ScmCustomerOrderItemsMapper scmCustomerOrderItemsMapper;
    @Autowired
    private IScmCustomerQuotesService scmCustomerQuotesService;
    @Autowired
    private IScmCustomerOrdersService scmCustomerOrdersService;
    @Autowired
    private IScmProjectProductsService scmProjectProductsService;

    /**
     * 查询客户订单明细
     * 
     * @param itemId 客户订单明细主键
     * @return 客户订单明细
     */
    @Override
    public ScmCustomerOrderItems selectScmCustomerOrderItemsByItemId(Long itemId)
    {
        return scmCustomerOrderItemsMapper.selectScmCustomerOrderItemsByItemId(itemId);
    }

    /**
     * 查询客户订单明细列表
     * 
     * @param scmCustomerOrderItems 客户订单明细
     * @return 客户订单明细
     */
    @Override
    public List<ScmCustomerOrderItems> selectScmCustomerOrderItemsList(ScmCustomerOrderItems scmCustomerOrderItems)
    {
        return scmCustomerOrderItemsMapper.selectScmCustomerOrderItemsList(scmCustomerOrderItems);
    }

    @Override
    public List<ScmCustomerOrderItemsWithOrderInfoVO> selectScmSupplierOrderItemsListWithOrderInfo(ScmCustomerOrderItemsWithOrderInfoVO scmCustomerOrderItems)
    {
        return scmCustomerOrderItemsMapper.selectScmSupplierOrderItemsListWithOrderInfo(scmCustomerOrderItems);
    }


    /**
     * 新增客户订单明细
     * 
     * @param scmCustomerOrderItems 客户订单明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertScmCustomerOrderItems(ScmCustomerOrderItems scmCustomerOrderItems) throws Exception {
        scmCustomerOrderItems.setCreateTime(DateUtils.getNowDate());
        scmCustomerOrderItems.setAmount(scmCustomerOrderItems.getUnitPrice().multiply(scmCustomerOrderItems.getQuantity()));
        int rows = scmCustomerOrderItemsMapper.insertScmCustomerOrderItems(scmCustomerOrderItems);
        if (rows == 0)
            return 0;
        if (scmCustomerOrderItems.getQuantity() != null &&  scmCustomerOrderItems.getUnitPrice().longValue() > 0){
            ScmCustomerOrders currentOder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrderItems.getOrderId());
            if (currentOder == null)
                throw new Exception(StringUtils.format("订单编号({})非法。 ", scmCustomerOrderItems.getOrderCode()));
            BigDecimal oldAmount = scmCustomerOrderItems.getAmount();
            BigDecimal newIncrementalAmount = scmCustomerOrderItems.getQuantity().multiply(scmCustomerOrderItems.getUnitPrice()).add(scmCustomerOrderItems.getMoldCost()).add(scmCustomerOrderItems.getJigCost());

            currentOder.setTotalAmount(oldAmount.add(newIncrementalAmount));
            scmCustomerOrdersService.updateScmCustomerOrders(currentOder);
        }
        return rows;
    }

    /**
     * 修改客户订单明细
     * 
     * @param scmCustomerOrderItems 客户订单明细
     * @return 结果
     */
    @Override
    public int updateScmCustomerOrderItems(ScmCustomerOrderItems scmCustomerOrderItems) throws Exception {
        ScmCustomerOrderItems oldScmCustomerOrderItems = scmCustomerOrderItemsMapper.selectScmCustomerOrderItemsByItemId(scmCustomerOrderItems.getItemId());

        scmCustomerOrderItems.setAmount(scmCustomerOrderItems.getUnitPrice().multiply(scmCustomerOrderItems.getQuantity()));
        scmCustomerOrderItems.setUpdateTime(DateUtils.getNowDate());
        int rows = scmCustomerOrderItemsMapper.updateScmCustomerOrderItems(scmCustomerOrderItems);
        if (rows == 0)
            return 0;
        if (scmCustomerOrderItems.getQuantity() != null &&  scmCustomerOrderItems.getUnitPrice().longValue() > 0){
            ScmCustomerOrders currentOrder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrderItems.getOrderId());
            if (currentOrder == null)
                throw new Exception(StringUtils.format("订单编号({})非法。 ", scmCustomerOrderItems.getOrderCode()));
            BigDecimal oldAmount = scmCustomerOrderItems.getAmount();
            BigDecimal oldIncrementalAmount = oldScmCustomerOrderItems.getAmount();
            BigDecimal newIncrementalAmount = scmCustomerOrderItems.getQuantity().multiply(scmCustomerOrderItems.getUnitPrice()).add(scmCustomerOrderItems.getMoldCost()).add(scmCustomerOrderItems.getJigCost());

            currentOrder.setTotalAmount(oldAmount.subtract(oldIncrementalAmount).add(newIncrementalAmount));
            scmCustomerOrdersService.updateScmCustomerOrders(currentOrder);
        }
        return rows;
    }

    /**
     * 批量删除客户订单明细
     * 
     * @param itemIds 需要删除的客户订单明细主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteScmCustomerOrderItemsByItemIds(Long[] itemIds)
    {
        return scmCustomerOrderItemsMapper.deleteScmCustomerOrderItemsByItemIds(itemIds);
    }

    /**
     * 删除客户订单明细信息
     * 
     * @param itemId 客户订单明细主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteScmCustomerOrderItemsByItemId(Long itemId)
    {
        return scmCustomerOrderItemsMapper.deleteScmCustomerOrderItemsByItemId(itemId);
    }

    /**
     * 报价单拉取
     *
     * @param scmCustomerOrder 客户订单明细
     * @return 订单明细
     */
    @Override
    @Transactional
    public int pullScmCustomerOrderItems(ScmCustomerOrders scmCustomerOrder) {
        // 检查订单输入数据，项目id和订单id不能为空
        if (scmCustomerOrder.getProjectId() == null || scmCustomerOrder.getId() == null) {
            return -1;
        }
        if (scmCustomerOrder.getId() == null || scmCustomerOrder.getId() == 0){
            throw new RuntimeException("订单编号不能为空");
        }
        ScmCustomerOrders currentOrder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrder.getId());
        // 根据项目id查询customerQuotesList
        List<ScmCustomerQuotes> scmCustomerQuotesList = scmCustomerQuotesService.selectScmCustomerQuotesListByProjectId(scmCustomerOrder.getProjectId());
        if (scmCustomerQuotesList == null) {
            return 0;
        }
        ScmProjectProducts scmProjectProducts;
        // 遍历查询的结果，组装客户订单信息并插入客户订单明细表
        ScmCustomerOrderItems scmCustomerOrderItems;
        int rows = 0;
        BigDecimal additionalAmount = BigDecimal.ZERO;
        for (ScmCustomerQuotes item : scmCustomerQuotesList){
            scmCustomerOrderItems = new ScmCustomerOrderItems();
            scmCustomerOrderItems.setOrderId(scmCustomerOrder.getId());
            scmCustomerOrderItems.setProductId(item.getProductId());
            scmCustomerOrderItems.setProjectProductId(item.getProjectProductId());
            scmCustomerOrderItems.setOrderCode(scmCustomerOrder.getOrderCode());
            scmCustomerOrderItems.setCustomerQuoteId(item.getId());
            scmCustomerOrderItems.setSupplierId(item.getSupplierId());
            scmCustomerOrderItems.setSupplierQuoteId(item.getSupplierQuoteId());
            scmCustomerOrderItems.setSupplierName(item.getSupplierName());
            scmProjectProducts =  scmProjectProductsService.selectScmProjectProductsById(item.getProjectProductId());
            scmCustomerOrderItems.setPurchaseCategory(scmProjectProducts.getPurchaseCategory());
            scmCustomerOrderItems.setDemandType(scmProjectProducts.getDemandType());
            scmCustomerOrderItems.setModel("");
            scmCustomerOrderItems.setManufactureNumber( "");
            scmCustomerOrderItems.setManufactureSubNumber( "");
            scmCustomerOrderItems.setDrawingNumberModel("");
            scmCustomerOrderItems.setDrawingVersion("");
            scmCustomerOrderItems.setProductName("");
            scmCustomerOrderItems.setMaterial(item.getMaterial());
            scmCustomerOrderItems.setSize("");
            scmCustomerOrderItems.setSpecification("");
            scmCustomerOrderItems.setColor("");
            scmCustomerOrderItems.setUnitPriceType(scmProjectProducts.getPurchaseCategory());
//            scmCustomerOrderItems.setUnitPrice(BigDecimal.valueOf(0));
            if (scmCustomerOrderItems.getUnitPriceType() == 1 || scmCustomerOrderItems.getUnitPriceType() == 2){
                scmCustomerOrderItems.setUnitPrice(item.getDisposableUnitPrice());
            }else if (scmCustomerOrderItems.getUnitPriceType() == 3){
                scmCustomerOrderItems.setUnitPrice(item.getTryUnitPrice());
            }else if (scmCustomerOrderItems.getUnitPriceType() == 4){
                scmCustomerOrderItems.setUnitPrice(item.getMassUnitPrice());
            }else {
                scmCustomerOrderItems.setUnitPrice(BigDecimal.ZERO);
            }
            scmCustomerOrderItems.setQuantity(BigDecimal.valueOf(0));
            scmCustomerOrderItems.setAmount(BigDecimal.valueOf(0));
            scmCustomerOrderItems.setMoldCost(item.getMoldCost());
            scmCustomerOrderItems.setJigCost(item.getJigCost());
            scmCustomerOrderItems.setRequestedDeliveryDate(currentOrder.getRequestedDeliveryDate());
            scmCustomerOrderItems.setRepliedDeliveryDate(currentOrder.getRepliedDeliveryDate());
            rows  += scmCustomerOrderItemsMapper.insertScmCustomerOrderItems(scmCustomerOrderItems);
        }

        return rows;
    }

    /**
     * 报价单选择
     *
     * @param scmCustomerOrder 客户订单明细
     * @return 订单明细
     */
    @Override
    @Transactional
    public int addScmCustomerOrderItemsFromQuotes(ScmCustomerOrders scmCustomerOrder, Long[] quotesIds) {
        if (scmCustomerOrder == null || quotesIds == null || quotesIds.length == 0 || scmCustomerOrder.getId() <= 0) {
            return -1;
        }
        ScmCustomerOrders currentOrder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrder.getId());
        ScmCustomerQuotes scmCustomerQuotes;
        ScmCustomerOrderItems scmCustomerOrderItems;
        ScmProjectProducts scmProjectProducts;
        int rows = 0;
        for (Long quoteId : quotesIds){
            scmCustomerQuotes = scmCustomerQuotesService.selectScmCustomerQuotesById(quoteId);
            if (scmCustomerQuotes == null)
                continue;
            scmCustomerOrderItems = new ScmCustomerOrderItems();
            scmCustomerOrderItems.setOrderId(scmCustomerOrder.getId());
            scmCustomerOrderItems.setProductId(scmCustomerQuotes.getProductId());
            scmCustomerOrderItems.setProjectProductId(scmCustomerQuotes.getProjectProductId());
            scmCustomerOrderItems.setOrderCode(scmCustomerOrder.getOrderCode());
            scmCustomerOrderItems.setCustomerQuoteId(scmCustomerQuotes.getId());
            scmCustomerOrderItems.setSupplierId(scmCustomerQuotes.getSupplierId());
            scmCustomerOrderItems.setSupplierQuoteId(scmCustomerQuotes.getId());
            scmCustomerOrderItems.setSupplierName(scmCustomerQuotes.getSupplierName());
            scmProjectProducts =  scmProjectProductsService.selectScmProjectProductsById(scmCustomerQuotes.getProjectProductId());
            scmCustomerOrderItems.setPurchaseCategory(scmProjectProducts.getPurchaseCategory());
            scmCustomerOrderItems.setDemandType(scmProjectProducts.getDemandType());
            scmCustomerOrderItems.setModel("");
            scmCustomerOrderItems.setManufactureNumber( "");
            scmCustomerOrderItems.setManufactureSubNumber( "");
            scmCustomerOrderItems.setDrawingNumberModel("");
            scmCustomerOrderItems.setDrawingVersion("");
            scmCustomerOrderItems.setProductName("");
            scmCustomerOrderItems.setMaterial(scmCustomerQuotes.getMaterial());
            scmCustomerOrderItems.setSize("");
            scmCustomerOrderItems.setSpecification("");
            scmCustomerOrderItems.setColor("");
            scmCustomerOrderItems.setUnitPriceType(scmProjectProducts.getPurchaseCategory());
//            scmCustomerOrderItems.setUnitPrice(BigDecimal.valueOf(0));
            if (scmCustomerOrderItems.getUnitPriceType() == 1 || scmCustomerOrderItems.getUnitPriceType() == 2){
                scmCustomerOrderItems.setUnitPrice(scmCustomerQuotes.getDisposableUnitPrice());
            }else if (scmCustomerOrderItems.getUnitPriceType() == 3){
                scmCustomerOrderItems.setUnitPrice(scmCustomerQuotes.getTryUnitPrice());
            }else if (scmCustomerOrderItems.getUnitPriceType() == 4){
                scmCustomerOrderItems.setUnitPrice(scmCustomerQuotes.getMassUnitPrice());
            }else {
                scmCustomerOrderItems.setUnitPrice(BigDecimal.ZERO);
            }
            scmCustomerOrderItems.setQuantity(BigDecimal.valueOf(0));
            scmCustomerOrderItems.setAmount(BigDecimal.valueOf(0));
            scmCustomerOrderItems.setMoldCost(scmCustomerQuotes.getMoldCost());
            scmCustomerOrderItems.setJigCost(scmCustomerQuotes.getJigCost());
            scmCustomerOrderItems.setRequestedDeliveryDate(currentOrder.getRequestedDeliveryDate());
            scmCustomerOrderItems.setRepliedDeliveryDate(currentOrder.getRepliedDeliveryDate());
            rows  += scmCustomerOrderItemsMapper.insertScmCustomerOrderItems(scmCustomerOrderItems);
        }
        return rows;
    }

    /**
     * 从历史订单中选择
     *
     * @param scmCustomerOrder 客户订单明细
     * @return 订单明细
     */
    @Override
    @Transactional
    public int addScmCustomerOrderItemsFromOrderItems(ScmCustomerOrders scmCustomerOrder, Long[] ids) {
        if (scmCustomerOrder == null || ids == null || ids.length == 0 || scmCustomerOrder.getId() <= 0) {
            return -1;
        }
        ScmCustomerOrders currentOrder = scmCustomerOrdersService.selectScmCustomerOrdersById(scmCustomerOrder.getId());
        ScmCustomerOrderItems oldItem;
        ScmCustomerOrderItems newItem;
        int rows = 0;
        for (Long itemId : ids){
            oldItem = scmCustomerOrderItemsMapper.selectScmCustomerOrderItemsByItemId(itemId);
            if (oldItem == null)
                continue;
            newItem = new ScmCustomerOrderItems();
            newItem.setOrderId(currentOrder.getId());
            newItem.setProductId(oldItem.getProductId());
            newItem.setProjectProductId(oldItem.getProjectProductId());
            newItem.setOrderCode(currentOrder.getOrderCode());
            newItem.setCustomerQuoteId(oldItem.getCustomerQuoteId());
            newItem.setSupplierId(oldItem.getSupplierId());
            newItem.setSupplierQuoteId(oldItem.getSupplierQuoteId());
            newItem.setSupplierName(oldItem.getSupplierName());
            newItem.setPurchaseCategory(oldItem.getPurchaseCategory());
            newItem.setDemandType( oldItem.getDemandType());
            newItem.setModel( oldItem.getModel());
            newItem.setManufactureNumber( oldItem.getManufactureNumber());
            newItem.setManufactureSubNumber( oldItem.getManufactureSubNumber());
            newItem.setDrawingNumberModel( oldItem.getDrawingNumberModel());
            newItem.setDrawingVersion( oldItem.getDrawingVersion());
            newItem.setProductName( oldItem.getProductName());
            newItem.setMaterial( oldItem.getMaterial());
            newItem.setSize( oldItem.getSize());
            newItem.setSpecification( oldItem.getSpecification());
            newItem.setColor(oldItem.getColor());
            newItem.setUnitPriceType(oldItem.getUnitPriceType());
            newItem.setUnitPrice(oldItem.getUnitPrice());
            newItem.setQuantity(BigDecimal.valueOf(0));
            newItem.setAmount(BigDecimal.valueOf(0));
            newItem.setMoldCost(oldItem.getMoldCost());
            newItem.setJigCost(oldItem.getJigCost());
            newItem.setRequestedDeliveryDate(currentOrder.getRequestedDeliveryDate());
            newItem.setRepliedDeliveryDate(currentOrder.getRepliedDeliveryDate());
            rows  += scmCustomerOrderItemsMapper.insertScmCustomerOrderItems(newItem);
        }
        return rows;
    }


}
